import router from "@/router";
//进度条
import NProgress from "nprogress";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import { isRelogin } from "@/utils/request";
import { usePermissionStore } from "@/stores/permission.js";
import "nprogress/nprogress.css";
import { getToken, setToken, removeToken } from "@/utils/token";
NProgress.configure({ showSpinner: false });
const whiteList = ["/login", "/register"];
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    if (to.path == "/login") {
      next("/");
      NProgress.done();
    } else if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true;
        useUserStore()
          .getInfo()
          .then(() => {
            isRelogin.show = false;
            usePermissionStore()
              .generateRoutes()
              .then((accessRoutes) => {
                accessRoutes.forEach((route) => {
                  if (!isHttp(route.path)) {
                    router.addRoute(route);
                  }
                });
                if (to.fullPath == "/") {
                  var heardPath =
                    accessRoutes[0].path.split("/")[1] == ""
                      ? ""
                      : accessRoutes[0].path;
                  let pathIndex =
                    heardPath +
                    "/" +
                    getDeepestChildPath(accessRoutes[0].children[0]);
                  console.log(pathIndex, "去哪");

                  next({ path: pathIndex, replace: true }); // hack方法 确保addRoutes已完成
                } else {
                  next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
                }
              });
          })
          .catch((err) => {
            useUserStore()
              .logOut()
              .then(() => {
                ElMessage.error(err);
                next({ path: "/login" });
              });
          });
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`login?redirect=${to.fullPath}`);
      NProgress.done();
    }
  }
});
router.afterEach(() => {
  NProgress.done();
});
function isHttp(url) {
  //判断是不是http外联
  return url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1;
}
function getDeepestChildPath(route) {
  if (route.children && route.children.length > 0) {
    return route.path + "/" + getDeepestChildPath(route.children[0]);
  }
  return route.path;
}
